Fix crash when calling type[Any] from dict.get()#20586
Fix crash when calling type[Any] from dict.get()#20586byteforge38 wants to merge 1 commit intopython:masterfrom
Conversation
6d12836 to
c0fcad8
Compare
test-data/unit/check-classes.test
Outdated
| # Regression test for https://github.com/python/mypy/issues/20585 | ||
| from typing import Any | ||
| op: type[Any] | ||
| reveal_type({0: object}.get(0, op)()) # N: Revealed type is "builtins.object" |
There was a problem hiding this comment.
I would have expected Any, not object. Is there a way to reproduce the crash without relying on .get()? And did you verify this line crashed without the fix? Our fixture may be simpler than the actual typeshed stubs for dict.get.
There was a problem hiding this comment.
I added two unit tests to mypy/test/testtypes.py, and yes, I was able to reproduce that crash
This comment has been minimized.
This comment has been minimized.
c0fcad8 to
4224b93
Compare
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
A5rocks
left a comment
There was a problem hiding this comment.
I don't like the object return but it sounds like that will need some special casing :/
hauntsaninja
left a comment
There was a problem hiding this comment.
Not sure this is right, could you test some cases where we have a class with __new__ that returns Any and see if that class can still be used to instantiate / passed to type?
I tested classes with class MyClass:
def __new__(cls) -> Any:
return super().__new__(cls)
x = MyClass() # ✓ Revealed type is MyClass
t: type[MyClass] = MyClass # ✓ Works
Protocol instantiation check also still works:
class MyProtocol(Protocol):
def method(self) -> int: ...
MyProtocol() # ✓ Error: "Cannot instantiate protocol class"It only skips the protocol/abstract class checks in |
Fixes #20585
When a callable has
type[Any]as its return type (e.g., fromdict.get(key, type[Any])), calling it would crash withAssertionError: isinstance(ret, Instance).The issue was in
is_type_obj()which returnedTruefortype[Any]becausetypeis a metaclass andAnyTypeisn'tUninhabitedType. However,type_object()then failed because it expects anInstance, notAnyType.The fix excludes
AnyTypefromis_type_obj()since we can't determine a concrete type object when the return type isAny.Contribution by Gittensor, see my contribution statistics at https://gittensor.io/miners/details?githubId=4217675